package com.cangxuan.app.ui.fragment;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;

import com.alibaba.fastjson.JSONObject;
import com.cangxuan.app.R;
import com.cangxuan.app.entity.User;
import com.cangxuan.app.ui.LoginActivity;
import com.cangxuan.app.ui.user.*;
import com.cangxuan.app.utils.DeviceUtils;
import com.cangxuan.app.utils.HttpUtils;
import com.cangxuan.app.utils.UserUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * Author: 杨刚、田凯
 * Activity: 我的片断
 * 我的 片断
 */
public class MineFragment extends Fragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    ConstraintLayout linear1; //身份认证
    ConstraintLayout linear2; //我的客服
    ConstraintLayout linear3; //关于藏选
    ConstraintLayout linear4; //分享藏选
    ConstraintLayout linear5; //设置

    ImageView head; //头像
    TextView txtNickname; //昵称
    TextView txtUid; //UID
    TextView txtLine; //分割线

    TextView txtBlockchainAddress; //区块链地址
    ImageView imgCopy; //复制
    View cang;  //我的藏品
    View bag;  //我的钱包
    View order;  //我的订单
    TextView getBlockChainBtn; //获取区块链地址

    Button btnMyLogin;
    TextView txtRealName;

    boolean logined = false;
    Handler handler = new Handler();

    User user1;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View parentView = inflater.inflate(R.layout.fragment_mine, container, false);
        //获取上下文
        Context context = getContext();
        linear1 = parentView.findViewById(R.id.linear1);
        linear2 = parentView.findViewById(R.id.linear2);
        linear3 = parentView.findViewById(R.id.linear3);
        linear4 = parentView.findViewById(R.id.linear4);
        linear5 = parentView.findViewById(R.id.linear5);
        btnMyLogin = parentView.findViewById(R.id.btn_myLogin);
        head = parentView.findViewById(R.id.image);
        cang = parentView.findViewById(R.id.cang);
        bag = parentView.findViewById(R.id.bag);
        order = parentView.findViewById(R.id.order);
        txtNickname = parentView.findViewById(R.id.txt_nickname);
        txtUid = parentView.findViewById(R.id.txt_uid);
        txtBlockchainAddress = parentView.findViewById(R.id.txt_blockchainAddress);
        txtLine = parentView.findViewById(R.id.txt_line);
        imgCopy = parentView.findViewById(R.id.img_copy);
        txtRealName = parentView.findViewById(R.id.txtRealName);
        getBlockChainBtn = parentView.findViewById(R.id.getBlockChainBtn);

        ActivityResultLauncher<Intent> setActivityResultLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == 1) {
                        loadUserInfo(context);
                    }
                });

        linear1.setOnClickListener(view -> {
            if (!logined) {
                Toast.makeText(context, "请先登录", Toast.LENGTH_SHORT).show();
                return;
            }
            user1 = UserUtils.getUser(context);
            Log.i("MineFargment", "点击了身份认证");

            if (user1.isHasSetRealname()) {
                Toast.makeText(context, "已实名无需再实名", Toast.LENGTH_SHORT).show();
            } else {
                Intent intent = new Intent(context, MyIdentityActivity.class);
                setActivityResultLauncher.launch(intent);
            }

        });
        linear2.setOnClickListener(view -> {
            if (!logined) {
                Toast.makeText(context, "请先登录", Toast.LENGTH_SHORT).show();
                return;
            }
            Log.i("MineFargment", "点击了我的客服");
            Intent intent = new Intent(context, MyKefuActivity.class);
            startActivity(intent);
        });
        linear3.setOnClickListener(view -> {
            if (!logined) {
                Toast.makeText(context, "请先登录", Toast.LENGTH_SHORT).show();
                return;
            }
            Log.i("MineFargment", "点击了关于藏选");
            Intent intent = new Intent(context, MyAboutActivity.class);
            startActivity(intent);
        });
        linear4.setOnClickListener(view -> {
            if (!logined) {
                Toast.makeText(context, "请先登录", Toast.LENGTH_SHORT).show();
                return;
            }
            Log.i("MineFargment", "点击了分享藏选");
        });


        linear5.setOnClickListener(view -> {
            if (!logined) {
                Toast.makeText(context, "请先登录", Toast.LENGTH_SHORT).show();
                return;
            }
            Log.i("MineFargment", "点击了设置");
            Intent intent = new Intent(context, MySetActivity.class);
            setActivityResultLauncher.launch(intent);
        });

        ActivityResultLauncher<Intent> activityResultLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == 1) {
                        //说明登录成功
                        User user = (User) result.getData().getSerializableExtra("user");
                        Log.i("登录结果", "登录成功!");
                        Log.i("登录结果", "用户信息：" + user.toString());
                        UserUtils.setUser(context, user);
                        loadUserInfo(context);
                    } else {
                        Log.i("登录结果", "未完成登录");
                    }
                });
        btnMyLogin.setOnClickListener(view -> {
            Intent intent = new Intent(context, LoginActivity.class);
            activityResultLauncher.launch(intent);
        });


        cang.setOnClickListener(view -> {
            if (!logined) {
                Toast.makeText(context, "请先登录", Toast.LENGTH_SHORT).show();
                return;
            }
            Intent intent = new Intent(context, MyCollectionActivity.class);
            startActivity(intent);
        });
        bag.setOnClickListener(view -> {
            if (!logined) {
                Toast.makeText(context, "请先登录", Toast.LENGTH_SHORT).show();
                return;
            }
            Intent intent = new Intent(context, MyWalletActivity.class);
            startActivity(intent);
        });
        order.setOnClickListener(view -> {
            if (!logined) {
                Toast.makeText(context, "请先登录", Toast.LENGTH_SHORT).show();
                return;
            }
            Intent intent = new Intent(context, MyOrderActivity.class);
            startActivity(intent);
        });
        getBlockChainBtn.setOnClickListener(view -> {
            User user = UserUtils.getUser(context);

            System.out.println(user.toString());
            //判断是否实名
            new Thread(()->{
                handler.post(()->{
                    ProgressDialog progressDialog = new ProgressDialog(context);
                    progressDialog.setMessage("正在获取区块链地址");
                });
                Map<String,String> header = new HashMap<>();
                header.put("Authorization", DeviceUtils.getDeviceID());
                String jsonString = HttpUtils.get("/api/user/getBlockchain/" + user.getId(),header);
                JSONObject jsonResponse = JSONObject.parseObject(jsonString);
                if (jsonResponse.getInteger("status") != 200){
                    handler.post(()->{
                        AlertDialog alertDialog = new AlertDialog.Builder(context).setTitle("获取失败").
                                setMessage(jsonResponse.getString("message")).setNegativeButton("确定", (dialogInterface, i) -> {

                                }).create();
                        alertDialog.show();
                        System.out.println(jsonString);
                    });
                }else{
                    handler.post(()->{
                        Toast.makeText(context,"获取成功",Toast.LENGTH_SHORT).show();
                        String blockAddress = jsonResponse.getString("message");
                        user.setBlockchainAddress(blockAddress);
                        UserUtils.setUser(context,user);
                        System.out.println("-------------");
                        loadUserInfo(context);
                    });
                }

            }).start();
        });
        imgCopy.setOnClickListener(view -> {
            ClipboardManager clipboardManager = (ClipboardManager)context.getSystemService(Context.CLIPBOARD_SERVICE);
            clipboardManager.setPrimaryClip(ClipData.newPlainText(null, txtBlockchainAddress.getText().toString().substring(6)));
            Toast.makeText(context,"复制成功",Toast.LENGTH_SHORT).show();
        });
        return parentView;
    }

    @Override
    public void onStart() {
        super.onStart();
        loadUserInfo(getContext());
    }

    public void loadUserInfo(Context context) {
        User user = UserUtils.getUser(context);
        Log.i("loadUserInfo  user", user + "");
        if (user != null) {
            txtNickname.setText(user.getNickname());
            txtNickname.setVisibility(View.VISIBLE); //显示昵称
            txtUid.setText("UID:" + user.getId());
            txtUid.setVisibility(View.VISIBLE); //显示UID
            if (user.getBlockchainAddress() != null) {
                txtBlockchainAddress.setText("区块链地址：" + user.getBlockchainAddress());
                txtBlockchainAddress.setVisibility(View.VISIBLE); //显示区块链地址
                imgCopy.setVisibility(View.VISIBLE); //显示copy图标
                getBlockChainBtn.setVisibility(View.GONE);
            } else {
                getBlockChainBtn.setVisibility(View.VISIBLE); //显示区块链地址
            }
            txtLine.setVisibility(View.VISIBLE); //显示分割线
            head.setVisibility(View.VISIBLE); //显示头像
            btnMyLogin.setVisibility(View.GONE); //隐藏登录按钮
            txtRealName.setText(user.isHasSetRealname() ? "已实名" : "未实名");
            logined = true;
        } else {
            Toast.makeText(context, "请先登录", Toast.LENGTH_SHORT).show();
            txtUid.setVisibility(View.GONE);
            txtNickname.setVisibility(View.GONE);
            txtBlockchainAddress.setVisibility(View.GONE);
            txtLine.setVisibility(View.GONE); //显示分割线
            imgCopy.setVisibility(View.GONE); //显示copy图标
            head.setVisibility(View.GONE); //显示头像
            getBlockChainBtn.setVisibility(View.GONE); //显示头像
            btnMyLogin.setVisibility(View.VISIBLE); //隐藏登录按钮
            logined = false;
        }
    }
}